<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * Version :  v1.0.0
 * Date    :  2023/5/31 14:48
 */

namespace App\Exception\Handler;

use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Codec\Json;
use Throwable;


class ValidationExceptionHandler extends ExceptionHandler
{
    /**
     * @var $config 配置对象
     */
    protected $config;

    /**
     * @var $container 容器对象
     */
    protected $container;

    /**
     * @var $http_code_config http状态码配置
     */
    protected $http_code_config;

    public function __construct()
    {
        $this->container = ApplicationContext::getContainer();
        $this->config = $this->container->get(ConfigInterface::class);
        $this->http_code_config = $this->config->get('http_code');
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();
        if ($throwable instanceof ValidationException) {
            $body = $throwable->validator->errors()->first();
            if (! $response->hasHeader("content-type")) {
                $response = $response->withAddedHeader("content-type", "text/plain; charset=utf-8");
            }
            return $response->withStatus((int)$this->http_code_config["unprocessable_entity"])
                ->withBody(new SwooleStream(Json::encode(["code"=>1,"message"=>$body])));
        }
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}